﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using School.Entities;
using School.Common;
using System.Data.Entity;
using School.Admission;
using School.Accounting;


namespace School.Pages.Admission
{
    public partial class Voucher : System.Web.UI.Page
    {
        //***************** This is function to handle page when page load ***************************
        //-**********************************************************************




        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(1023) == true)
                {
                    if (!(Page.IsPostBack))
                    {
                        //security
                        Fillcrls();

                        InitializeControls();

                        GridDataBind();

                    }

                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }
        # region "Collect Data"

        //***************** This is function to bind data grid  ***************************
        //-**************************************************************************
        protected void GridDataBind()
        {
            Int32 mycount;
            
            Hashtable SearchTable = new Hashtable();
            if (txtSearchNumber.Text.Length > 0)
            {
                SearchTable.Add("Number", txtSearchNumber.Text.ToString());
            }
            if (txtSearchPayment_Order_Number.Text.Length > 0)
            {
                SearchTable.Add("Payment_Order_Number", txtSearchPayment_Order_Number.Text.ToString());
            }
            if (txtSearchStudent_Id.Text.Length > 0)
            {
                SearchTable.Add("Student_Id", txtSearchStudent_Id.Text.ToString());
            }

            if (txtSearchDate.Text.Length > 0)
            {
                SearchTable.Add("Date", txtSearchDate.Text.ToString());
            }
            griddata.DataSource = ACCVoucher.All(SearchTable);

            griddata.DataBind();
            griddata.Visible = true;
            mycount = griddata.Rows.Count;
            lblRecordNo.Text = "عدد نتائج البحث = " + mycount.ToString();
            if (mycount == 0)
            {
                lblMessage.Text = "لا يوجد بيانات";
            }
            else
            {
                lblMessage.Text = "";
            }

        }

        # endregion


        # region "Fill all crls"

        //***************** This is function to fill crl  ***************************
        //-**************************************************************************

        protected void Fillcrls()
        {

            ddlExpense_Id.DataSource = Expense.GetAllExpenses();
            ddlExpense_Id.DataTextField = "Name";
            ddlExpense_Id.DataValueField = "ID";
            ddlExpense_Id.DataBind();

            ddlcampus_Id.DataSource = Structure.GetCampuses();
            ddlcampus_Id.DataTextField = "Name";
            ddlcampus_Id.DataValueField = "Id";
            ddlcampus_Id.DataBind();
            ddlcampus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

            ddlSearchcampus_Id.DataSource = Structure.GetCampuses();
            ddlSearchcampus_Id.DataTextField = "Name";
            ddlSearchcampus_Id.DataValueField = "Id";
            ddlSearchcampus_Id.DataBind();
            ddlcampus_Id.Items.Insert(0, new ListItem("اختيار", "-1"));


            ddlSearchGrade_ID.DataSource = Structure.GetGrades();
            ddlSearchGrade_ID.DataTextField = "Name";
            ddlSearchGrade_ID.DataValueField = "id";
            ddlSearchGrade_ID.DataBind();

                
            ddlSearchStage_Id .DataSource = Structure.GetGrades();
            ddlSearchStage_Id .DataTextField = "Name";
            ddlSearchStage_Id .DataValueField = "id";
            ddlSearchStage_Id .DataBind();


        }


        //***************** This is function to initlaize crl  ***************************
        //-**************************************************************************
        protected void InitializeControls()
        {
            txtFirstName.Text = "";
            txtSecondName.Text = "";
            txtThirdName.Text = "";
            txtFourthName.Text = "";

            
        }

        # endregion


        # region "Mode Handlers"

        //***************** This is function to handle page in add mode  ***************************
        //-**************************************************************************
        protected void PutFormInAddMode()
        {
            txtFirstName.Text = "";
            txtSecondName.Text = "";
            txtThirdName.Text = "";
            txtFourthName.Text = "";
        }


        //***************** This is function to handle page in brows mode  ***************************
        //-**************************************************************************

        protected void PutFormInBrwosMode()
        {
            pnlAdd.Visible = false;
            pnlbrows.Visible = false;

        }

        #endregion


        # region "Grid Events ***********"

        //***************** This is function to handle page when Page Index Changing   ***************************
        //-**************************************************************************

        protected void griddata_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            griddata.PageIndex = e.NewPageIndex;
            GridDataBind();
        }


        //***************** This is function to handle page when Row Deleting  ***************************
        //-**************************************************************************

        protected void griddata_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                griddata.SelectedIndex = e.RowIndex;

                long CID = Int32.Parse(griddata.SelectedDataKey.Value.ToString());
                Boolean successadd = FileOrder.Delete(CID);
                if (successadd == true)
                {
                    GridDataBind();
                    lblMessage.Visible = true;
                    lblMessage.Text = "تم حذف البيانات بنجاح";

                }
            }
            catch (Exception)
            {
                lblMessage.Text = "  لم يتم حذف البيانات بنجاح رجاء مراجعة مدير النظام";

            }

        }


        //***************** This is function to handle page when Row Data Bound  ***************************
        //-**************************************************************************
        protected void griddata_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton LB = (LinkButton)e.Row.FindControl("LinkButton1");
                LB.Attributes.Add("onclick", "javascript:return " +
                "confirm('Are you sure you want to delete record(s) ( " +
                DataBinder.Eval(e.Row.DataItem, "Number") + " ) ?')");

            }
        }

        protected void griddata_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlAdd.Visible = false;
            pnlbrows.Visible = false;
            pnldetails.Visible = true;
            DetailsView1bind();

        }

        protected void DetailsView1bind()
        {
            Hashtable SearchTable = new Hashtable();
            if (txtSearchNumber.Text.Length > 0)
            {
                SearchTable.Add("Number", griddata.SelectedDataKey.Value.ToString());
            }
            
            DetViewdata.DataSource = ACCVoucher.All(SearchTable);
            DetViewdata.DataBind();
        }



        # endregion



        # region   "Execute commands sent to the form"



        //***************** This is function to handle page when Puser click in الغاء btn  ***************************
        //-**************************************************************************
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtFirstName.Text = "";
            txtSecondName.Text = "";

        }


        //***************** This is function to handle page when Puser click in اضافة btn  ***************************
        //-**************************************************************************

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            pnlAdd.Visible = true;
            pnlbrows.Visible = false;
            pnldetails.Visible = false;
        }

        //***************** This is function to handle page when Puser click in انهاء btn  ***************************
        //-**************************************************************************


        protected void btnend_Click(object sender, EventArgs e)
        {
            btnAdd.Visible = true;
            pnlAdd.Visible = false;
            pnlbrows.Visible = true;
        }
        //***************** This is function to handle page when Puser click in حفظ btn  ***************************
        //-**************************************************************************

        protected void btnSave_Click(object sender, EventArgs e)
        {

            Hashtable SearchTable = new Hashtable();
            if (txtSearchPayment_Order_Number.Text.Length > 0)
            {
                SearchTable.Add("Payment_Order_Number", txtSearchPayment_Order_Number.Text.ToString());
            }
            if (ACCVoucher.All(SearchTable).Count() == 0)
            {

                DateTime dt = Convert.ToDateTime(txtDate.Text);
                Int32 Expense_Id = Convert.ToInt32(ddlExpense_Id.SelectedValue);

                int Is_active, is_closed;
                if (CHKIs_Active.Checked == true)
                {
                    Is_active = 1;
                }
                else
                {
                    Is_active = 0;
                }
                if (CHIs_Closed.Checked == true)
                {
                    is_closed = 1;
                }
                else
                {
                    is_closed = 0;
                }

                String fileNumber;
                fileNumber = String.Format("{00}", ddlcampus_Id.SelectedValue);
                fileNumber += String.Format("{00}", ddlCertificate_Id.SelectedValue);
                DateTime dt1 = Convert.ToDateTime(txtDate.Text);

                fileNumber += String.Format("{0:ddMMyy}", dt1);
                fileNumber += String.Format("{0000}", Student.MaxID() + 1);
                Int64 studentId;
                studentId = Student.AddFromVoucher(new TE_Student
                {
                    FileNumber = Convert.ToInt64(fileNumber),
                    Campus_Id = Convert.ToInt64(ddlcampus_Id.SelectedValue),
                    Certificate_Id = Convert.ToInt64(ddlCertificate_Id.SelectedValue),
                    Stage_Id = Convert.ToInt32(ddlcampus_Id.SelectedValue),
                    Grade_ID = Convert.ToInt32(ddlGrade_Id.SelectedValue),
                    Ar_FirstName = txtFirstName.Text,
                    Ar_SecondName = txtSecondName.Text,
                    Ar_ThirdNmae = txtThirdName.Text,
                    Ar_FourthName = txtFourthName.Text
                });
                Int64 xx = ACCVoucher.Add(new ACC_Voucher() { Date = dt, Payment_Order_Number = Convert.ToInt32(txtPayment_Order_Number.Text), Student_Id = studentId, Expense_Id = Expense_Id, Value = Convert.ToDecimal("10.000"), Detail = txtDetail.Text, Is_Active = CHKIs_Active.Checked, Is_Closed = CHIs_Closed.Checked });
                txtShowCampus.Text = ddlcampus_Id.SelectedItem.Text;
                txtShowCertificate.Text = ddlCertificate_Id.SelectedItem.Text;
                txtShowGrade.Text = ddlGrade_Id.SelectedItem.Text;
                txtShowStage.Text = ddlStage_Id.SelectedItem.Text;
                txtShowName.Text = txtFirstName.Text + " " + txtSecondName.Text + " ";
                txtShowDate.Text = txtDate.Text;
                txtShowValue.Text = txtValue.Text;
                txtShowNumber.Text = xx.ToString();
                txtShowDetail.Text = txtDetail.Text;

                lblMessage.Text = "تم حفظ البيانات بنجاح";
                pnlAdd.Visible = false;
                pnldetails.Visible = true;
            }
            else
            {
                lblErrorMessage.Text = "هذا الرقم تم ادخال الفاتورة الخاصة به سابقا";

            }

        }


        # endregion



        # region " Search *********************"




        //***************** This is function to search by  Get All btn ***************************
        //-**************************************************************************
        protected void btnGetAll_Click(object sender, EventArgs e)
        {
            
            
            GridDataBind();
        }


        
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            GridDataBind();
        }

        # endregion

     
        protected void ddlStage_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlStage_Id.SelectedIndex > 0)
            {
                ddlGrade_Id.Items.Clear();
                ddlGrade_Id.DataSource = Structure.GetGradesByStage(Convert.ToInt64(ddlStage_Id.SelectedValue));
                ddlGrade_Id.DataTextField = "Name";
                ddlGrade_Id.DataValueField = "id";
                ddlGrade_Id.DataBind();
                ddlGrade_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlGrade_Id.Enabled = true;
            }
        }

       

        protected void txtShowCampus_TextChanged(object sender, EventArgs e)
        {

        }

        protected void ddlSearchcampus_Id_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void txtPayment_Order_Number_TextChanged(object sender, EventArgs e)
        {
            
            ADM_File_Order PayNo = FileOrder.Single(Convert.ToInt32 ( txtPayment_Order_Number.Text));
            if (PayNo == null)
            {
                txtPayment_Order_Number.Text = "";
                lblErrorMessage.Text = "هذا الرقم غير موجود";
                ddlcampus_Id.Items.Clear();
                ddlCertificate_Id.Items.Clear();
                ddlStage_Id.Items.Clear();
                ddlGrade_Id.Items.Clear();
                txtFirstName.Text = "";
                txtSecondName.Text = "";
                txtThirdName.Text = "";
                txtFourthName.Text = "";
                lblErrorMessage.Visible = true;
            }else
            {
                ddlcampus_Id.SelectedIndex =ddlcampus_Id.Items.IndexOf(ddlcampus_Id.Items.FindByValue(PayNo.Campus_Id.ToString()));
                ddlCertificate_Id.SelectedIndex = ddlCertificate_Id.Items.IndexOf(ddlCertificate_Id.Items.FindByValue(PayNo.Certificate_Id.ToString()));
                ddlStage_Id.SelectedIndex = ddlStage_Id.Items.IndexOf(ddlStage_Id.Items.FindByValue(PayNo.Stage_Id.ToString()));
                ddlGrade_Id.SelectedIndex = ddlGrade_Id.Items.IndexOf(ddlGrade_Id.Items.FindByValue(PayNo.Grade_Id.ToString()));

                ddlExpense_Id.SelectedIndex = ddlExpense_Id.Items.IndexOf(ddlExpense_Id.Items.FindByValue("20"));
                txtFirstName.Text = PayNo.FirstName.ToString();
                txtSecondName.Text = PayNo.SecondName.ToString();
                txtThirdName.Text = PayNo.ThirdName.ToString();
                txtFourthName.Text = PayNo.FourthName.ToString();
                txtValue.Text = PayNo.Price.ToString();
                lblErrorMessage.Visible = false;
            }
            

        }

        protected void txtSearchNumber_TextChanged(object sender, EventArgs e)
        {

        }

        protected void ddlcampus_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlcampus_Id.SelectedIndex > 0)
            {

                ddlCertificate_Id.Items.Clear();
                ddlStage_Id.Items.Clear();
                ddlGrade_Id.Items.Clear();

                ddlCertificate_Id.DataSource = Structure.GetCertificatesByCampus(Convert.ToInt64(ddlcampus_Id.SelectedValue));
                ddlCertificate_Id.DataTextField = "Name";
                ddlCertificate_Id.DataValueField = "Id";
                ddlCertificate_Id.DataBind();
                ddlCertificate_Id.Items.Insert(0, new ListItem("اختيار", "-1"));

                ddlCertificate_Id.Enabled = true;
                ddlStage_Id.Enabled = false;
                ddlGrade_Id.Enabled = false;

            }
        }

        protected void ddlCertificate_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCertificate_Id.SelectedIndex > 0)
            {
                ddlStage_Id.Items.Clear();
                ddlGrade_Id.Items.Clear();

                ddlStage_Id.DataSource = Structure.GetStagesByCertificate(Convert.ToInt64(ddlCertificate_Id.SelectedValue));
                ddlStage_Id.DataTextField = "Name";
                ddlStage_Id.DataValueField = "id";
                ddlStage_Id.DataBind();
                ddlStage_Id.Items.Insert(0, new ListItem("اختيار", "-1"));
                ddlStage_Id.Enabled = true;
                ddlGrade_Id.Enabled = false;


            }

        }





        

        


    }
}